<?php

class Generic {

    private $ArrBulan = Array(
        1 => "Januari",
        2 => "Februari",
        3 => "Maret",
        4 => "April",
        5 => "Mei",
        5 => "Mei",
        6 => "Juni",
        7 => "Juli",
        8 => "Agustus",
        9 => "September",
        10 => "Oktober",
        11 => "November",
        12 => "Desember");

    function sendHttpRequest($uri, $port = 80, $content = "", $isPostMethod = false, $return_transfer = true) {

        $CI = &get_instance();
        
        $CI->db->close();
        
        try
        {
            $url_post = curl_init();

            if ($isPostMethod) {
                curl_setopt($url_post, CURLOPT_URL, $uri);
                curl_setopt($url_post, CURLOPT_PORT, $port);
                curl_setopt($url_post, CURLOPT_HEADER, FALSE);
                curl_setopt($url_post, CURLOPT_POST, $isPostMethod);
                curl_setopt($url_post, CURLOPT_POSTFIELDS, $content);
            } else {
                curl_setopt($url_post, CURLOPT_URL, $uri . "?" . $content);
                curl_setopt($url_post, CURLOPT_PORT, $port);
            }
            curl_setopt($url_post, CURLOPT_RETURNTRANSFER, $return_transfer);
//            curl_setopt($url_post, CURLOPT_CONNECTTIMEOUT, 5);
//            curl_setopt($url_post, CURLOPT_TIMEOUT, 5);


            $response = curl_exec($url_post);
            $errorno = curl_getinfo($url_post, CURLINFO_HTTP_CODE);
            $errormsg = curl_error($url_post);

            if ($errorno !== 200)
                $response = "Gagal";
            /*
              else
              $response  = "Berhasil";
             * 
             */
        }catch(Exception $e){}
        
        $CI->db->reconnect();
        
        return $response;
    }

   


    function createFileConf($host, $port, $path, $filename, $content) {
        $out = "";
        $uri .= "http://";                  // protokol
        $uri .= $host;                      // host address
        $uri .= $port == "" ? ":80" : ":" . $port;  // port, default 80
        $uri .= $path;
        $filename = $uri . "/" . $filename;

//if (is_writable($filename)) {
        if (!$handle = fopen($filename, 'w')) {
            return "Gagal membuka file ($filename)";
            exit;
        }

// Write $somecontent to our opened file.
        if (fwrite($handle, $content) === FALSE) {
            return "Gagal menulis ke file ($filename)";
            exit;
        }

        $out = "Berhasil, menulis ($content) ke file ($filename)";

        fclose($handle);

//}else{
//    $out = "Gagal, tidak mendapat akses file ($filename)";
//}

        return $out;
    }

    function qryStrKirim($arrExclude) {
        $qryStr = "";
//$arrAddQryStr = !is_array($arrAddQryStr) ? array(""):$arrAddQryStr;
        $arrExclude = array_combine($arrExclude, $arrExclude);
        $arrQryStr = $_GET;
        $newArrQryStr = array_diff_key($arrQryStr, $arrExclude);

//debugQuery($arrQryStr);
//debugQuery($newArrQryStr);

        if (is_array($newArrQryStr)) {
//$newArrQryStr = array_merge($newArrQryStr, $arrAddQryStr);
            foreach ($newArrQryStr as $key => $val) {
                $qryStr .= $qryStr == "" ? $key . "=" . $val : "&" . $key . "=" . $val;
            }
        }
        return $qryStr;
    }

# set page title

    function setPageTitle($title) {
        global $__CFG_page_title;

        $__CFG_page_title = $title;
    }

# timer function

    function get_timer() {
        list($usec, $sec) = explode(" ", microtime());

        return ((float) $usec + (float) $sec);
    }

    function format_angka($angka, $delim = ".") {
        return number_format($angka, 0, "", $delim);
    }
    
    function object_to_array($object)
        {
            if(is_array($object) || is_object($object))
            {
                $array = array();
                foreach($object as $key => $value)
            {
                $array[$key] = Generic::object_to_array($value);
            }
                return $array;
            }
            return $object;
        }

#creating combo dropdown

    function createCombo($result, $rowData, $fieldval = "", $fieldstring = "", $nama = "", $kode = "", $addOption = "", $addAction = "") {
        $hasil = "<select name=\"" . $nama . "\" id=\"" . $nama . "\" " . $addAction . ">";
        if ($addOption != "")
            $hasil .= $addOption;
        if ($rowData > 0) {
            foreach ($result as $line) {
                $hasil .= "<option value=\"" . $line->$fieldval . "\"" . ($line->$fieldval == $kode ? " selected" : "") . ">" . $line->$fieldstring . "</option>";
            }
        }
        $hasil .= "</select>";

        return $hasil;
    }

    function createComboArray($elmName, $arr, $val, $opt = "", $event = "") {
        $out = '<select name="' . $elmName . '" id="' . $elmName . '" ' . $event . ' >';
        $out .= isset($opt) ? $opt : '<option value="">--Pilih--</option>';
        foreach ($arr as $value) {
            $out .= '<option value="' . $value . '" ' . ($val == $value ? 'selected' : '') . '>' . $value . '</option>';
        }
        $out.="</select>";
        return $out;
    }

    function createComboArray2($elmName, $arr, $val, $opt = "", $event = "") {
        $out = '<select name="' . $elmName . '" id="' . $elmName . '" ' . $event . ' >';
//$out .= $opt <> ""?$opt:'<option value="-1">&nbsp;</option>';
        foreach ($arr as $key => $value) {
            $out .= '<option value="' . $key . '" ' . ($val == $key ? 'selected' : '') . '>' . $value . '</option>';
        }
        $out.="</select>";
        return $out;
    }

    function getAge($dob, $tdate) {
        $age = 0;
        while ($tdate > $dob = strtotime('+1 year', $dob)) {
            ++$age;
        }
        return $age;
    }

#get name of data master

    function getNamaMaster($kode, $t_master) {
        global $dbi;

        $sql = "select " . $t_master . " as nama from " . $t_master . " where kode = '" . $kode . "'";
        $row = $dbi->get_row($sql);

        return $row->nama;
    }

    function getNama($kode, $t_name, $t_field, $whereField = "", $opr = "") {
        global $dbi;
        $whereField = $whereField == "" ? "kode" : $whereField;
        if ($opr != "") {
            $sql = "select " . $t_field . " as nama from " . $t_name . " where " . $whereField . " like('%" . $kode . "%')";
        } else {
            $sql = "select " . $t_field . " as nama from " . $t_name . " where " . $whereField . " = '" . $kode . "'";
        }
//echo $sql;
        $row = $dbi->get_row($sql);

        return $row->nama;
    }

    function getScalar($sql, $fieldselected = "f") {
        global $dbi;
//echo $sql;
        return $dbi->get_row($sql)->$fieldselected;
    }

#get date last "n" days

    function getlastdays($currdate, $numdays) {

        $date_array = getdate(strtotime($currdate));
        $time_date = $date_array[0];

        $returndate = date("Y-m-d", $time_date - ($numdays * 24 * 60 * 60));

        return $returndate;
    }

//format tanggal inputan dd-mm-yyyy

    function formatInt2DB($angka, $delim = "") {
        $delim = $delim != "" ? $delim : ".";
        $angka = $delim != "" ? str_replace($delim, "", $angka) : $angka;
        if (is_numeric($angka))
            return $angka;
        else
            return 0;
    }

    function formatDate2DB($tgl, $iswaktu = false) {
        $arrTgl = explode(" ", $tgl);
        $tgle = $arrTgl[0];
        $wkte = $arrTgl[1];

        list($tanggal, $bulan, $tahun) = explode("-", $tgle);

        if ($tgl != "")
            return $tahun . "-" . $bulan . "-" . $tanggal . ($iswaktu ? $wkte : "");
        else
            return "";
    }

//format tanggal inputan yyyy-mm-dd
    function formatDB2Date($tgl, $iswaktu = false, $isbahasa = false) {
        //global $ArrBulan;
        $tgl = trim($tgl);
        $arrTgl = explode(" ", $tgl);
        $tgle = $arrTgl[0];
        if(isset($arrTgl[1])) $wkte = substr($arrTgl[1], 0, 8); else $wkte ='';
        
        list($tahun, $bulan, $tanggal) = explode("-", $tgle);

        if ($tgl != "") {
            if (!$isbahasa)
                return $tanggal . "-" . $bulan . "-" . $tahun . ($iswaktu ? " " . $wkte : "");
            else
                return $tanggal . " " . $this->ArrBulan[intval($bulan)] . " " . $tahun;
        }
        else
            return "";
    }
	
	function toArray($data) { // posisi sementara
        if (is_object($data))
            $data = get_object_vars($data);
        return is_array($data) ? array_map($this->__FUNCTION__, $data) : $data;
    }
    
    function RequestMessage($url, $vals){

        $CI = &get_instance();
        
        $CI->db->close();
        
        try
        {
            $ch = curl_init();

            //set the url, number of POST vars, POST data
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_POST,count($vals));
            curl_setopt($ch,CURLOPT_POSTFIELDS,$vals);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
            //execute post
            $result = curl_exec($ch);

            //close connection
            curl_close($ch);
        }catch(Exception $e){}
        
        $CI->db->reconnect();
        
	return $result;
    }

    function stringToArrayObject($str) {
        $arr1 = explode("<;>", $str);
        $arrCols = explode("<#>", $arr1[0]);
        for ($i = 1; $i < sizeof($arr1); $i++) {
            $arrBaris = explode("<#>", $arr1[$i]);
            $x = 0;
            $y = $i - 1;
            foreach ($arrCols as $cols) {
                $arrData[$y]->$cols = $arrBaris[$x];
                $x++;
            }
        }

        return $arrData;
    }

    function AddOptions($start, $end, $value) {
        for ($i = $start; $i <= $end; $i++) {
            ?>
            <option value="<?php echo $i ?>"<?php echo ($i == $value ? " selected" : "") ?>><?php echo $i ?></option>
            <?php
        }
    }

    function TreeMenu($kode_induk) {
        global $dbi, $auth, $__CFG_http_adminroot;
        $sql = "select * from mt_menu where id_menu_induk " . ($kode_induk == "" ? "is NULL" : "= " . QuotedStringTrim($kode_induk)) . " AND is_active='1' ORDER BY urutan";
        $row = $dbi->query($sql);
        $count = sizeof($row);

        if ($count > 0) {
            foreach ($row as $r) {
                $kode = $r->id_menu;
                $induk = $r->id_menu_induk;
                $nama = $r->menu;
                $url = $r->link;
                $nama2 = str_replace("{userid}", " &raquo;<span class=\"tebal2\">" . $auth->getUsername() . "</span>", $nama);
                $url = str_replace("{root}", $__CFG_http_adminroot, $url);
                $url = str_replace("{userid}", $auth->getUserID(), $url);
                $sqli = "select id_menu from mt_menu where id_menu_induk = " . QuotedStringTrim($kode);
                $rowi = $dbi->query($sqli);
                $havechild = (sizeof($rowi) > 0);
//if($auth->IsViewAccess($kode)) {
                echo "<li><a href=\"" . $url . "\" title=\"" . $nama . "\" " .
                ($havechild ? "class=\"menu-induk\"" : "") . ">" . $nama2 . "</a>";
                if ($havechild)
                    echo "<ul>";
                TreeMenu($r->id_menu);
                if ($havechild)
                    echo "</ul>";
                echo "</li>";
//}
            }
        }
    }

    function ComboMenu($kode_induk, $selected) {
        global $dbi;
        $sql = "select * from app_menus where kode_induk " . ($kode_induk == "" ? "is NULL" : "= " . QuotedStringTrim($kode_induk));
        $row = $dbi->get_results($sql);
        $count = sizeof($row);
        if ($count > 0) {
            foreach ($row as $r) {
                $cchar = strlen($r->kode_app_menus);
                $cstrip = $cchar / 2 - 1;
                $menu = "<option value=\"" . $r->kode_app_menus . "\" " . ($r->kode_app_menus == $selected ? "selected=\"selected\"" : "") . ">";
                for ($i = 0; $i < $cstrip; $i++)
                    $menu .= "- ";
                $menu .= $r->nama;
                $menu .= "</option>";
                echo $menu;
                ComboMenu($r->kode_app_menus, $selected);
            }
        }
    }

    function TableMenu($kode_induk, $gridcss = "GridItem2") {
        
    }

    function JSTextMask($arrElm, $arrMask) {
        ?>
        <script src="<?php echo $__CFG_http_js; ?>T_JQuery.min.js"></script>
        <script src="<?php echo $__CFG_http_js ?>jquery.maskedinput-1.2.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function()
            {
        <?php
        if (sizeof($arrElm) > 0 && sizeof($arrMask)) {
            for ($x = 0; $x < sizeof($arrElm); $x++) {
                ?>
                        $("#<?php echo $arrElm[x] ?>").mask("<?php echo $arrMask[x] ?>");
                <?php
            }
        }
        ?>
            });
        </script>
        <?php
    }

    function GiveAttributeNot($elm, $value, $attr) {
        $hasil = "";
        if ($elm != $value) {
            $hasil = $attr;
        }

        return $hasil;
    }

    function GiveAttribute($elm, $value, $attr) {
        $hasil = "";
        if ($elm == $value) {
            $hasil = $attr;
        }

        return $hasil;
    }

    function dateFormat($date, $format = "") {
        //global $ArrBulan;

        $dts = explode(" ", $date);
        $d = explode("-", $dts[0]);
        $t = explode(":", $dts[1]);
        $bln = (int) $d[1];

        return str_pad($d[2], 2, "0", 0) . " " . $this->ArrBulan[$bln] . " " . $d[0];
    }

    function sortingField($title, $sf, $sf_curr, $sd_curr) {
        $cfs = $_GET["fs"];
        $cfv = $_GET["fv"];
        $addLink = "";
        if ($cfs != "" && $cfv != "")
            $addLink = "&fs=" . $cfs . "&fv=" . $cfv;
        $sd = "DESC";
        if ($sf == $sf_curr && $sd == $sd_curr)
            $sd = "ASC";
        $link = "<a class=\"sorting " . strtolower($sd) . "\" href=\"?csf=" . $sf . "&csd=" . $sd . $addLink . "\" title=\"Sorting " . $title . " " . $sd . "\">" . $title . "</a>";

        return $link;
    }

    function getTitleInfo($kode_staff = "") {
        global $auth;
        if ($kode_staff == "")
            $kode_staff = $auth->getUserID();
        $nama = getNama($kode_staff, "pegawai", "nama", "userid");
        $nrp = getNama($kode_staff, "pegawai", "nrp", "userid");

        return $nama . "/" . ($nrp == "" ? "-" : $nrp);
    }

    function GenerateNomorUsulan($max, $nomor) {
        return $nomor . date("Y") . str_pad(($max + 1), 4, "0", 0);
    }

    function dateFormatIndo($tgl) {
        return "";
    }

    function QuotedString($str) {
        return "'" . str_replace("'", "''", $str) . "'";
    }

    function QuotedStringTrim($str) {
        return QuotedString(trim($str));
    }

    function RedirectPageJS($targeturl) {
        echo "<scr" . "ipt>window.location.href = '" . $targeturl . "';</scr" . "ipt>";
    }

    function debugQuery($var, $show_queries = false) {
        global $dbi;
        echo "<pre>";
        print_r($var);
        echo "</pre>";
        $dbi->show_queries = $show_queries;
    }

    function getTipeProgres($id_status_request) {
        return getScalar("SELECT id_tipe_progres FROM mt_status_request WHERE id_status_request='" . $id_status_request . "'", "id_tipe_progres");
    }

    function getStatusRequest($id_status_request_old) {
        global $auth;

        $tipe_user = $auth->getRole();
        if ($tipe_user == 3) {
            $out = "'38', '39', '40', '41'";
        } elseif ($tipe_user == 2) {
            $out = "'34', '35', '36', '37'";
        } else {
            $out = "'31', '32', '33'";
        }

        return $out;
    }
	
    function fillItIfEmpty($varTest ,$filled) { 
            if(''==$varTest)
                    return $filled;
            else	
                    return $varTest;
    }
    
    function dc_diff_date($start_datetime, $end_datetime, $out_as_array = false){
        $intervalo = date_diff(date_create($start_datetime), date_create($end_datetime));
        $out = $intervalo->format("%y tahun, %m bulan, %d hari, %h jam, %i menit, %s detik");
        if(!$out_as_array)
            return $out;

        $arr_out = explode(", ", $out);
        $arr_result = array();
        foreach($arr_out as $value){
            $val_ = explode(" ", $value);
            if($val_[0] >= 1)
                $arr_result[] = $value;
        }

        if(count($arr_result) > 0)
            return $arr_result;
        else
            return array($arr_out[5]);
    }

}
?>
